package demo02;

import demo01.TestThread2;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import static java.util.concurrent.Executors.*;

/**
 * @author mubei
 * @date 2021/11/20
 * @description 测试 Callable 创建线程
 */
public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;
    public TestCallable(String url,String name){
        this.url = url;
        this.name = name;
    }
    @Override
    public Boolean call(){
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("图片下载完成"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestCallable t1 = new TestCallable("url", "name");
        TestCallable t2 = new TestCallable("url", "name");
        TestCallable t3 = new TestCallable("url", "name");

        // 创建执行服务
        ExecutorService ser = newFixedThreadPool(3);

        // 提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t1);
        Future<Boolean> r3 = ser.submit(t1);

        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r1.get();
        boolean rs3 = r1.get();

        // 关闭服务
        ser.shutdown();
    }
}


class WebDownloader{
    //下载方法
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
